package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luhao
 * @ClassName GlobalExceptionHandler.java
 * @Description 全局异常拦截器
 * @createTime 2023/5/18
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(XuChengException.class)
    @ResponseStatus
    public RestErrorResponse xueChengExceptionHandler(XuChengException exception){
        log.error("出现异常:{}",exception.getMessage());
        return new RestErrorResponse(exception.getMessage(),exception.getErrCode());
    }
    @ExceptionHandler(Exception.class)
    @ResponseStatus
    public RestErrorResponse globalHandler(Exception exception){
        log.error("出现异常:{}",exception.getMessage());
        return new RestErrorResponse(exception.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus
    public RestErrorResponse methodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        List<FieldError> errors = bindingResult.getFieldErrors();
        List<String> errorMsgs = new ArrayList<>();
        errors.stream().forEach(item -> {
            errorMsgs.add(item.getDefaultMessage());
        });
        String join = StringUtils.join(errorMsgs, ",");
        log.error("出现异常:{}", exception.getMessage());
        return new RestErrorResponse(join);
    }
    @ResponseStatus
    @ExceptionHandler(SQLException.class)
    public RestErrorResponse sqlException(SQLException exception){
        log.error("出现异常：{}",exception);
        return new RestErrorResponse("sql语法出现错误");
    }
}
